﻿using DevExpress.DataAccess.Json;
using DevExpress.XtraEditors.Filtering;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReportDesignerServer.Common;
using ReportDesignerServer.DataModels;
using ReportDesignerServer.IRepository;
using ReportDesignerServer.Repository;
using SqlSugar;

namespace ReportDesignerServer.Services
{
    public class DataSourceService
    {
        //private readonly IPrintModelDatasrcRepository datasrcRepository;

        private readonly IPrintModelDataRepository datasrcRepository;
        public DataSourceService(IPrintModelDataRepository datasrcRepository)
        {
            this.datasrcRepository = datasrcRepository;
        }
        /// <summary>
        /// 获取数据源
        /// </summary>
        /// <param name="modelName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public JsonDataSource GetJsonDataSource(string modelName, object[]? args = null)
        {
            var dataSrcList = datasrcRepository.GetModelDatasrcs(modelName);

            JObject jObject = new JObject();
            dataSrcList?.ForEach(a =>
            {
                var sql = args == null ? a.DataSourceBing : string.Format(a.DataSourceBing, args);
                if (a.DataSrcType == 2)
                {
                    var data = datasrcRepository.RowToCol(sql);
                    jObject.Add(a.DataSourceEnName, JToken.FromObject(data));
                }
                else
                {
                    var data = datasrcRepository.Select(sql);
                    jObject.Add(a.DataSourceEnName, JToken.FromObject(data));
                }

            });
            var json = JsonConvert.SerializeObject(jObject);  
            return CreateDataSourceFromText(json);
        }

        /// <summary>
        /// 创建数据源
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private static JsonDataSource CreateDataSourceFromText(string json)
        {
            var jsonDataSource = new JsonDataSource();
            // Specify the object that retrieves JSON data.
            jsonDataSource.JsonSource = new CustomJsonSource(json);
            // Populate the data source with data.
            jsonDataSource.Fill();
            NLogHelper.GetLog().Info("数据源json:" + json);
            return jsonDataSource;
        }
    }
}
